/**
 * Global exception handler for the application.
 * This class handles various exceptions that may occur during the execution of the application.
 * @author hylexus
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * Handles generic throwable exceptions.
     * @param e The throwable exception
     * @return Response with server error status
     */
    @ExceptionHandler(Throwable.class)
    public Resp<Object> processThrowable(Throwable e) {
        log.error(e.getMessage(), e);
        return Resp.failure(DefaultRespCode.SERVER_ERROR);
    }

    /**
     * Handles JtSessionNotFoundException.
     * @param exception The JtSessionNotFoundException
     * @return Response with session not found error status
     */
    @ExceptionHandler(JtSessionNotFoundException.class)
    public Resp<Object> processJtSessionNotFoundException(JtSessionNotFoundException exception) {
        return Resp.failure(SESSION_NOT_FOUND, "No session found with terminalId [" + exception.getTerminalId() + "]");
    }

    /**
     * Handles WebExchangeBindException.
     * @param exception The WebExchangeBindException
     * @return Response with parameter error message
     */
    @ExceptionHandler(WebExchangeBindException.class)
    public Resp<Object> processWebExchangeBindException(WebExchangeBindException exception) {

        final BindingResult bindingResult = exception.getBindingResult();
        final String errorMsg = bindingResult.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("; "));

        return Resp.parameterError(errorMsg);
    }
}
